package jdmx.framework.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jdmx.framework.common.Envelope;
import jdmx.framework.common.Handler;
import jdmx.framework.common.constants.Const;
import jdmx.library.da.Database;

public abstract class Dao extends Handler {
    protected Database db = null;	
    
	protected String sqlForCreate = null;
	protected String sqlForRead = null;
	protected String sqlForUpdate = null;
	protected String sqlForDelete = null;

	/**
	 * Initializeaza obiectul Dao
	 */
	@Override
	public void init(String handlingCode)
	{
		super.init(handlingCode);
		if (db == null) db = ServiceContext.getDatabase(Const.DB_MAIN);
	}
	
	/**
	 * Intoarce stringul sql. Poate fi suprascrisa pentru a hard-coda stringul sql pentru un anumit dao.
	 * @param entityName
	 * @param statementName
	 * @return sql
	 */
	public String getSql(String entityName, String statementName) {
		return ServiceContext.getSql(entityName, statementName);
	}	

	public Envelope execute(Envelope envelope) {
		String methodName = envelope.methodName;
		Envelope resultEnvelope = null;
		
		Method method = null;
		try {
			method = (Method) this.getClass().getMethod(methodName, Envelope.class);
		} catch (IllegalArgumentException e1) {
		} catch (SecurityException e1) {
		} catch (NoSuchMethodException e) {
		}		
		
		if (method != null) {
			try {
				resultEnvelope = (Envelope) method.invoke(this, envelope);
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			} catch (InvocationTargetException e) {
			}
		}

		return resultEnvelope;
	}
	
	public Envelope create(Envelope envelope) 
	{
		if (sqlForCreate == null)
			sqlForCreate = getSql(handlingCode, Const.SQL_CREATE);
		return null;
	}

	public Envelope read(Envelope envelope) 
	{
		if (sqlForRead == null)
			sqlForRead = getSql(handlingCode, "Read") ;
		return null;
	}
	
	public Envelope update(Envelope envelope) 
	{
		if (sqlForUpdate == null)
			sqlForUpdate = getSql(handlingCode, "Update");
		return null;
	}
	
	public Envelope delete(Envelope envelope)
	{
		if (sqlForDelete == null)
			sqlForDelete = getSql(handlingCode, "Delete");
		return null;
	}
}
